package thread;

import java.util.concurrent.*;

/**
 * 知道如何(解耦合的)启动线程
 *   >Runnable 无返回值
 *   >Callable 返回值
 *
 * new Thread( Runnable.class ) 业务进行采取额外类(匿名内部类)调用执行
 * Pool.submit( Callable.class ) return Future<Object>.get();
 *
 * @author yuank
 * @date 2024/12/24 18:14:17
 */
class ThreadStart {
    public static void main(String[] args) {
        /**1 old**/
        new Thread(new method1())
                .start();
        new Thread(new method2())
                .start();

        /**2 分开代码逻辑与线程接口**/
        new Thread(()
                -> {new method3().runX();})
                .start();

        new Thread(()
                -> {new method4().runY();})
                .start();
    }
}

class method1 implements Runnable { public synchronized void run() {}}
class method2 implements Runnable { public synchronized void run() {}}

class method3{ public synchronized void runX() {}}
class method4{ public synchronized void runY() {}}




//携带返回值
class callable{
    ExecutorService pool = Executors.newSingleThreadExecutor();

    public void run() throws ExecutionException, InterruptedException {
        //执行方法
        Callable<Long> callable = () -> {return 43L;};

        //提交
        Future<Long> futureSubmit = pool.submit(callable);//模板方法 +适配器 此处很重要FutureTask

        //模拟耗时
        System.out.println("异步等待线程池执行任务中-");
        Thread.sleep(1000);

        //异步等待
        System.out.println(futureSubmit.get());
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        new callable().run();
    }
}